<template>
  <div ref="editorContainer" id="code-editor"></div>
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import { onMounted, onUnmounted, ref, toRaw, watch } from "vue";
//编辑器容器
const editorContainer = ref(null);
//编辑器实例
const editor = ref(null);

//编辑器内容(代码)
const value = ref("// 这里是初始代码");

interface Props {
  language?: string;
  handleChange: (val: string) => void;
}

// eslint-disable-next-line no-undef
const props = withDefaults(defineProps<Props>(), {
  language: () => "java",
  handleChange: (val: string) => {
    console.log(val);
  },
});

watch(
  () => props.language,
  () => {
    if (editor.value) {
      monaco.editor.setModelLanguage(
        toRaw(editor.value).getModel(),
        props.language
      );
    }
  }
);

//初始化编辑器
onMounted(() => {
  //编辑器初始化
  if (editorContainer.value) {
    editor.value = monaco.editor.create(editorContainer.value, {
      value: value.value,
      language: props.language,
      theme: "vs-dark",
      readOnly: false,
      folding: true, // 代码折叠
      snippetSuggestions: "inline", // 代码提示
      tabCompletion: "on", // 代码提示按tab完成
    });
  }
  // 编辑器内容变更时回调
  editor.value.onDidChangeModelContent(() => {
    // 获取编辑器内容
    props.handleChange(toRaw(editor.value).getValue());
  });
});

// 当组件被卸载时调用该回调函数
onUnmounted(() => {
  // 检查 editor 是否已初始化
  if (editor.value) {
    // 清理 editor 资源，避免内存泄漏
    console.log("code-editor执行卸载");
    toRaw(editor.value).dispose();
  }
});
</script>

<style scoped>
#code-editor {
  width: 100%;
  min-height: 400px;
}
</style>
